<template>
  <div class="scoreParticulars">
    <div class="scoreOperate">
      <div class="scoreCollect" v-if="!scoreData.FAVORITE_ID" @click.stop.prevent="enshrineScoreToLibrary(scoreData)">
        <img src="http://mobuz-mp.cdn.bcebos.com/matter/not_like@2x.png">
      </div>
      <div class="scoreCollect" v-if="scoreData.FAVORITE_ID" @click.stop.prevent="removalScoreFromLibrary(scoreData)">
        <img src="http://mobuz-mp.cdn.bcebos.com/matter/like@2x.png">
      </div>
      <div class="scoreDownload" @click.stop.prevent="downloadAccredit" v-if="showDownLoad">
        <img src="http://mobuz-mp.cdn.bcebos.com/matter/download@2x.png">
      </div>
    </div>
    <div class="scoreImage">
      <div class="imageCell" v-for="(item, index) in scoreImage" :key="index">
        <img :src="item" lazy-load  mode="widthFix" @click.stop.prevent="previewImageList(item, scoreImage)">
      </div>
    </div>
  </div>
</template>

<script>
import {obtainScoreDetails, appendScoreToCollect, removeScoreToCollect, cumulativeHotOfScore} from '@/config/api'
import {showMessager, showPictureCard} from "@/config/wUtils"
// import {dateRegExp} from '@/config/mUtils'
export default {
  data () {
    return {
      // 曲谱数据
      scoreData: [],
      // 曲谱图片数据
      scoreImage: [],
      // 显示 下载按钮
      showDownLoad: false,
      // 下载 数目
      downloadCount: 0
    }
  },
  mounted () {},
  methods: {
    // 初始化 曲谱详情界面
    initScoreParticulars(){
      let self = this;
      console.log('初始化 曲谱详情界面', self.$root.$mp.query.score_id)
      self.scoreData = []
      if (self.$root.$mp.query.score_id) {
        // // 页面标题
        // wx.setNavigationBarTitle({
        //   title: '自定标题'
        // })

        // 累加 曲谱浏览量
        self.accumulateHotOfScore()
        // 获取 曲谱 详情
        self.acquireScoreDetails()
      }
    },

    // 累加 曲谱浏览量
    async accumulateHotOfScore() {
      let self = this;
      let hotInfo = await cumulativeHotOfScore(self.$root.$mp.query.score_id)
      console.log(hotInfo, '.......HotInfo')
      if (hotInfo.status === 200) {
        // 清空 本地 浏览的曲谱
        wx.removeStorageSync('browse_score')
        // 存储 本地 浏览的曲谱
        wx.setStorageSync('browse_score', self.$root.$mp.query.score_id);
      }
    },


    // 获取 曲谱 详情
    async acquireScoreDetails() {
      let self = this;
      // 本地用户信息
      const userInfo = await wx.getStorageSync('userInfo')
      if (JSON.stringify(userInfo) != '[]') { 
        wx.showNavigationBarLoading()
        // wx.showLoading({title: '加载中'})
        let scoreInfo = await obtainScoreDetails(self.$root.$mp.query.score_id, userInfo.openId, userInfo.unionId)
        console.log(scoreInfo, '.......scoreInfo')
        if (scoreInfo.status === 200) {
          // 曲谱库数据
          self.scoreData = scoreInfo.data
          if(self.scoreData.IMG) {
            // 曲谱图片数据
            self.scoreImage = self.scoreData.IMG.split(',')
            if (JSON.stringify(self.scoreImage) !== '[]') {
              // 显示 下载按钮
              self.showDownLoad = true
            }
          }
  
        }
        wx.hideNavigationBarLoading()
        wx.hideLoading()
        wx.stopPullDownRefresh()
      }
    },

    // 收藏 图谱到曲谱库
    async enshrineScoreToLibrary(item) {
      let self = this;
      self.$set(item, 'FAVORITE_ID', 10086)
      // 本地用户信息
      const userInfo = await wx.getStorageSync('userInfo')
      let collectState = await appendScoreToCollect(item.ID, userInfo.openId, userInfo.unionId)
      console.log(collectState, item, '搜藏 图谱到曲谱库')
      // 清空 本地 不收藏图谱
      wx.removeStorageSync('collect_false')
      // 存储 本地 收藏图谱
      wx.setStorageSync('collect_true', item.ID);
    },

    // 移除 图谱于曲谱库
    async removalScoreFromLibrary(item) {
      let self = this;
      self.$set(item, 'FAVORITE_ID', '')
      // 本地用户信息
      const userInfo = await wx.getStorageSync('userInfo')
      let collectState = await removeScoreToCollect(item.ID, userInfo.openId, userInfo.unionId)
      console.log(collectState, item, '移除 图谱于曲谱库')
      // 清空 本地 收藏图谱
      wx.removeStorageSync('collect_true')
      // 存储 本地 不收藏图谱
      wx.setStorageSync('collect_false', item.ID);
    },


    // 展示 图片列表
    previewImageList(item, itemList) {
      let self = this;
      showPictureCard(item, itemList)
    },
    // 下载操作  
    downloadOperate() {
      console.log('下载操作  ....')
      let self = this;
      let imgList = self.scoreImage
      // let imgList = ['https://mobuz-dev.oss-cn-hangzhou.aliyuncs.com/avatar/20181101_104916279_814.jpg', 'https://mobuz-dev.oss-cn-hangzhou.aliyuncs.com/avatar/20181101_105715388_286.jpg', 'http://mobuz-dev.oss-cn-hangzhou.aliyuncs.com/avatar/cursor_down.png', 'https://mobuz-dev.oss-cn-hangzhou.aliyuncs.com/avatar/20181101_104916279_814.jpg', 'https://mobuz-dev.oss-cn-hangzhou.aliyuncs.com/avatar/20181101_105715388_286.jpg', 'http://mobuz-dev.oss-cn-hangzhou.aliyuncs.com/avatar/cursor_down.png']  
      wx.showLoading({
          title: '图片下载中..',
      })
      let count = 0  
      for(let i=0,j=1; i<imgList.length; i++,j++){
        self.downloadImage(imgList[i], j, imgList.length, (text) => {
          // console.log(text, j , imgList.length, self.downloadCount, '................text')
          if (text === 100) {
            // wx.showLoading({
            //     title: j + '/'+ imgList.length + '下载中',
            //     duration:10000
            // })
            // if(j === imgList.length){
            //     wx.showToast({
            //         title: '下载完成',
            //         duration:1000
            //     })
            // }
            // wx.showLoading({
            //     title: self.downloadCount + '/'+ imgList.length + '下载中',
            //     duration:10000
            // })
            count ++
            console.log(self.downloadCount, count, imgList.length, '....imgList.length')
            if(count === imgList.length){
                wx.showToast({
                    title: '下载已完成',
                    duration:1000
                })
                self.downloadCount = 0
            }
          }else{
            wx.showToast({
                title: '下载失败 ~',
            })
          }
          console.log('拿到值了是'+ text );
        })
      }
    },
    // 下载授权
    downloadAccredit () {
      let self = this;
      // 获取用户授权设置
      wx.getSetting({
        success (res) {
          console.log(res.authSetting["scope.writePhotosAlbum"], '....获取用户授权设置')
          // 用户 未授权
          if (res.authSetting["scope.writePhotosAlbum"] === undefined) {
            // 下载操作 
            self.downloadOperate()
          }

          //  用户  同意授权
          if (res.authSetting["scope.writePhotosAlbum"] === true) {
            // 下载操作 
            self.downloadOperate()
          }

          // 用户  拒绝授权 再次同意
          if (res.authSetting["scope.writePhotosAlbum"] === false) {
            console.log('相册 未授权')
            // // 默认弹出授权
            // self.defaultAccredit()

            // 打开设置界面，引导用户开启授权。
            wx.openSetting({
              success (res) {
                console.log(res.authSetting, '....打开设置界面')
                // res.authSetting = {
                //   "scope.userInfo": true,
                //   "scope.userLocation": true
                // }
                if (res.authSetting["scope.writePhotosAlbum"] === true) {
                  // 下载操作 
                  self.downloadOperate()
                }
              }
            })
          }
        }
      })
    },  
    downloadImage (imageStr, i, listLength, callback) {
      let self = this;
      // console.log(imageStr.replace(/^http/,"https"), '..........')
      wx.authorize({
        scope: 'scope.writePhotosAlbum',
        success() {
          // 用户已经同意小程序使
          const downloadTask = wx.downloadFile({
            url: imageStr.replace(/^http/,"https"),
            success(res) {
              // var temp = res.tempFilePath
              wx.saveImageToPhotosAlbum({
                  filePath: res.tempFilePath,
                  success(res) {
                      console.log(res, 'success', self.downloadCount, i)
                      // 判断是否下载完成
                      // if(self.downloadCount == listLength){
                      //     self.downloadCount = 0
                      //     callback(100);
                      // }
                      callback(100);
                  },
                  fail(err){
                      wx.showToast({
                          title: '第' + i +'下载失败',
                      })
                  }
              })
            },
            fail(res) {
              console.log(res)
              wx.showToast({
                  title: '下载失败`',
              })
            }
          })

          downloadTask.onProgressUpdate((res) => {
            if(res.progress == 100){
              // callback(res.progress);
              let count = self.downloadCount
              self.downloadCount = count + 1
              // console.log(self.downloadCount, '.....self.downloadCount')
              // var count = that.data.percent_n;//统计下载多少次了
              // that.setData({
              //     percent_n:count+1
              // })
              // if (self.downloadCount == listLength){//判断是否下载完成
              //     // that.setData({//完成后，清空percent-N,防止多次下载后，出错
              //     // percent_n: 0
              //     // })
              //     // that.dowNum();
              //     self.downloadCount = 0
              // }
            }
          })
        },
        fail(){
          wx.showToast({
              title: '获取授权失败',
          })
        }
      })
    },
  },
  // // 下拉刷新
  // onPullDownRefresh () {
  //   let self = this;
  //   // 初始化 曲谱界面
  //   self.initMusicScore()
  // },
  // // 上拉加载
  // onReachBottom () {
  //   console.log('上拉加载')
  //   let self = this;
    
  // },
  // 页面显示
  onShow () {
    let self = this;
    console.log('页面显示')
    // 初始化 曲谱详情界面
    self.initScoreParticulars()
  }
}
</script>

<style lang="less" scoped>
.scoreParticulars{
  width: 100%;
  background: #ffffff;
  .scoreOperate{
    // position: fixed;
    position: absolute;
    // background: #ffffff;
    right:0;
    top:0;
    left:0;
    text-align:right;
    .scoreCollect{
      display: inline-block;
      vertical-align: middle;
      padding: 24rpx 10rpx;
      width: 30rpx;
      height: 27rpx;
      img{
        width: 100%;
        height: 100%;
        display: block;
      }
    }
    .scoreDownload{
      display: inline-block;
      vertical-align: middle;
      padding: 24rpx 10rpx;
      margin-right: 22rpx;
      width: 40rpx;
      height: 27rpx;
      img{
        width: 100%;
        height: 100%;
        display: block;
      }
    }
  }
  .scoreImage{
    width: 100%;
    .imageCell{
      width: 100%;
      img{
        width: 100%;
        height: auto;
        display: block;
      }
    }
  }
}
</style>
